<template>
  <div>
    <!--主体部分-->
    <div>
      <el-table
          ref="multipleTableRef"
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column width="70">
          <template #default="{ row }">
            <el-image
                style="width: 30px; height: 30px"
                :src="videoimage"
                v-if="row.fileCategory==1"
                fit="contain"/>
            <el-image
                style="width: 30px; height: 30px"
                :src="audioimage"
                v-if="row.fileCategory==2"
                fit="contain"/>
            <el-image
                style="width: 30px; height: 30px"
                :src="row.fileUrl"
                v-if="row.fileCategory==3"
                fit="contain"/>
            <el-image
                style="width: 30px; height: 30px"
                :src="documentimage"
                v-if="row.fileCategory == 4"
                fit="contain"
            />
            <el-image
                style="width: 30px; height: 30px"
                :src="othersimage"
                v-if="row.fileCategory == 5"
                fit="contain"
            />
            <el-image
                style="width: 30px; height: 30px"
                :src="folderimage"
                v-if="row.folderType == 1"
                fit="contain"
            />
          </template>
        </el-table-column>
        <el-table-column property="fileName" label="文件名"  width="200"></el-table-column>
        <el-table-column property="fileCategory" label="文件类型"  width="120" :formatter="fileTypeFormatter">
          <template #default="{ row }">
            <div v-if="row.folderType==1">文件夹</div>
          </template>
        </el-table-column>
        <el-table-column property="fileSize" label="文件大小"  width="120" :formatter="formatFileSize">
          <template #default="{ row }">
            <div v-if="row.folderType==1"></div>
          </template>
        </el-table-column>
        <el-table-column property="createTime" label="创建时间"  width="200" :formatter="formatDate"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <div v-if="row.folderType==0">
              <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  title="从回收站删除将会彻底删除，您确定要删除嘛？?"
                  @confirm="deleteToRecycle(row.fileId)">
                <template #reference>
                  <el-button size="small" type="danger" @click.stop>删除</el-button>
                </template>
              </el-popconfirm>
              <el-button size="small" type="success" @click.stop="recycle(row.fileId)">恢复</el-button>
            </div>
          </template>

        </el-table-column>

      </el-table>
    </div>
  </div>

  <el-dialog v-model="previewVisible" :show-close="true">
    <template #header="{ titleId, titleClass }">
      <div class="my-header">
        <h4 :id="titleId" :class="titleClass">文件预览</h4>
      </div>
    </template>
    <div style="display: flex;align-items: center;justify-content: center">
      <el-image style="width: 60%; height: 60%;"
                :src="preUrl"
                fit="contain"/>
    </div>
  </el-dialog>

  <el-dialog v-model="newFolderVisible" :show-close="true">
    <template #header="{ titleId, titleClass }">
      <div class="my-header">
        <h4 :id="titleId" :class="titleClass">新建文件夹命名</h4>
      </div>
    </template>
    <div style="display: flex;align-items: center;justify-content: center">
      <el-input v-model="newFolder.folderName"></el-input>
      <el-button type="success" @click="addFolder">确认创建</el-button>
    </div>
  </el-dialog>

  <el-dialog v-model="reNameVisible" :show-close="true">
    <template #header="{ titleId, titleClass }">
      <div class="my-header">
        <h4 :id="titleId" :class="titleClass">文件重命名</h4>
      </div>
    </template>
    <div style="display: flex;align-items: center;justify-content: center">
      <el-input v-model="reNameValue"></el-input>
      <el-button type="success" @click="reName">确认重命名</el-button>
    </div>
  </el-dialog>

  <el-dialog v-model="moveFileView" :show-close="true">
    <template #header="{ titleId, titleClass }">
      <div class="my-header">
        <h4 :id="titleId" :class="titleClass">请选择文件移动位置</h4>
      </div>
    </template>
    <div>
      <el-card class="box-card"
               style="max-width: 600px; margin: 20px auto; padding: 24px; box-shadow: 0 2px 12px rgba(0,0,0,0.1)">
        <div style="font-size: 18px; font-weight: 500; margin-bottom: 20px;color: #4da6e6">
          是否要将文件移动到：（{{ getCurrentFolderName() }}） 目录
        </div>

        <ul style="list-style: none; padding: 0; margin: 0;">
          <li v-for="folder in currentFolders" :key="folder.folderId"
              style="margin-bottom: 12px;">
            <el-button
                style="width: 100%; padding: 10px 16px; border-radius: 8px; border: 1px solid #e4e7ed; background: #fff; text-align: left; transition: all 0.2s;"
                :class="{ 'is-active': selectedFolderId === folder.folderId }"
                @click="selectFolder(folder.folderId)">
              {{ folder.folderName }}
            </el-button>
          </li>
        </ul>

        <el-button
            v-if="currentParentId!== null"
            @click="goBack"
            style="color: #606266; font-size: 14px; margin: 20px 0; padding: 8px 16px; border-radius: 4px; border: 1px solid #e4e7ed; background: #f8f9fa;">
          返回上一级目录
        </el-button>

        <div style="display: flex; justify-content: flex-end; margin-top: 24px;">
          <el-button
              type="success"
              plain
              @click="moveFile"
              style="padding: 12px 24px; font-size: 14px; border-radius: 6px; box-shadow: 0 2px 4px rgba(50,205,50,0.2);">
            确认移动
          </el-button>
        </div>
      </el-card>
    </div>


  </el-dialog>

  <el-dialog v-model="shareFileView" :show-close="true">
    <template #header="{ titleId, titleClass }">
      <div class="my-header">
        <h4 :id="titleId" :class="titleClass">分享</h4>
      </div>
    </template>
    <div style="display: flex;align-items: center;justify-content: center;flex-direction: column">

      <el-card class="box-card" style="width: 100%;display: flex;justify-content: center;" >
        <div>链接是: <span class="link-style">https://zhixiangyunpan.com/fileExample</span></div>

        <el-input clearable placeholder="请输入提取码" v-model="shareFIleRes.code" style="margin-top: 20px"></el-input>

        <div style="margin-top: 20px">
          <el-radio-group v-model="shareTimeRadio">
            <el-radio :value="1">1天</el-radio>
            <el-radio :value="7">7天</el-radio>
            <el-radio :value="30">永久</el-radio>
          </el-radio-group>
        </div>


      </el-card>

      <el-button type="success" style="margin-top: 30px" @click="shareFile">确认生成分享链接</el-button>

    </div>
  </el-dialog>

  <el-dialog v-model="bigFileView" :show-close="true">
    <template #header="{ titleId, titleClass }">
      <div class="my-header">
        <h4 :id="titleId" :class="titleClass">分片上传和断点续传</h4>
      </div>
    </template>
    <div class="singleFilePartUpload">
      <el-upload ref="uploadRef" name="files" action="#"
                 :on-change="selectSinglePartFile" :on-remove="removeSingleFilePart" :file-list="singleFilePart.fileList" :auto-upload="false">
        <el-button  slot="trigger" size="large" type="primary">选取文件</el-button>
        <div></div>
        <el-button style="margin-left: 10px;" size="large" type="success" @click.stop="singleFilePartUpload">点击进行单文件分片上传</el-button>
        <div slot="tip" class="el-upload__tip">文件分片上传</div>
        <el-progress :percentage="uploadProgress.percentage"  :text-inside="true" :stroke-width="30" style="width: 30%"/>
      </el-upload>
    </div>
    <div style="margin-top: 100px">
      <div class="multipleFilePartUpload">
        <el-upload ref="uploadRef" name="files" action="#"
                   :on-change="selectSingleFilePartPoint" :on-remove="removeSingleFilePartPoint" :file-list="singleFilePartPoint.fileList" :auto-upload="false">
          <el-button slot="trigger" size="large" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="large" :type="singleFilePartPoint.isStop? 'info':'success'" @click.stop="singleFilePartPointUpload">{{ singleFilePartPoint.isStop? '点击继续文件断点上传' : '点击进行文件断点上传' }}</el-button>
          <div slot="tip" class="el-upload__tip">单文件断点上传</div>
          <el-progress :percentage="uploadProgress.percentage1"  :text-inside="true" :stroke-width="30" style="width: 30%"/>
        </el-upload>
      </div>
    </div>
  </el-dialog>

</template>

<script setup>
import {ref, reactive, watch, onMounted} from "vue"
import request from "@/utils/request.js";
import {ElMessage} from 'element-plus'
import dayjs from 'dayjs';
import {computed} from 'vue';
import axios from "axios";
import SparkMD5 from 'spark-md5';

//数据定义------------------------------------------------

//表格和多选
const tableData = ref([]);
const multipleTableRef = ref();
const multipleSelection = ref([]);

const total = ref()

//预览
const previewVisible = ref(false)
const preUrl = ref();

//导航路径
const folders = ref([]);// 文件夹数据
const curFolderId = ref(1); // 当前文件夹ID
const newFolder = ref({});//新增的对象


//固定图标的显示
import documentImage from '@/assets/myimg/document.png';

const documentimage = ref(documentImage);
import videoImage from '@/assets/myimg/video.png'

const videoimage = ref(videoImage)
import audioImage from '@/assets/myimg/audio.png'

const audioimage = ref(audioImage)
import othersImage from '@/assets/myimg/others.png'

const othersimage = ref(othersImage)
import folderImage from '@/assets/myimg/folder.png'

const folderimage = ref(folderImage)

//无法预览提醒,中间商理论
import notPre from '@/assets/myimg/notPre.png'
//无需const notPreImage=ref(notPre)

//方法定义------------------------------------------------

//分页
const pageSize = ref(5)
const pageNum = ref(1)
// load 方法可以像这样定义
const load = () => {
  request.post("/file/recycleList").then(res => {
    console.log("当前的页面总量" + res.data.total)
    tableData.value = res.data;
    total.value = res.data.total
  })
};
// 修改 handleSizeChange 方法
const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`);
  pageSize.value = val;
  load(); // 假设 load() 是你需要调用的方法
};

// 修改 handleCurrentChange 方法
const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
  pageNum.value = val;
  load(); // 假设 load() 是你需要调用的方法
};


const init = () => {
  console.log("当前目录路径" + curFolderId.value);
  load()

  request.get('/folder/list')
      .then((res) => {
        console.log(res)
        folders.value = res.data;  // 将获取的数据存储在组件的 data 中
      })
      .catch((error) => {
        console.error('获取数据失败:', error);
      });
};
init();
// 时间格式化函数
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return '';
  return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss');
};
// 文件大小转换函数
const formatFileSize = (row, column, cellValue) => {
  if (!cellValue) return '0 B';
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  let i = 0;
  while (cellValue >= 1024 && i < sizes.length - 1) {
    cellValue /= 1024;
    i++;
  }
  return `${cellValue.toFixed(2)} ${sizes[i]}`;
};
// 类型转换函数
const VIDEO = 1;
const AUDIO = 2;
const IMAGE = 3;
const DOCUMENT = 4;
const OTHER = 5;
const fileTypeMap = {
  [VIDEO]: '视频',
  [AUDIO]: '音频',
  [IMAGE]: '图片',
  [DOCUMENT]: '文档',
  [OTHER]: '其他',
};
const fileTypeFormatter = (row, column, cellValue) => {
  return fileTypeMap[cellValue] || '未知';
};


//多选，后面写
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}


// 行点击事件
const handleRowClick = (row) => {
  console.log("当前行的数据:", row);
  if (row.fileCategory === 3) {
    preUrl.value = row.fileUrl
    previewVisible.value = !previewVisible.value
  } else if (row.folderType == 1) {
    console.log("我点击了文件夹")
    curFolderId.value = row.folderId
    //init();
    load()
    console.log("目前的目录：" + curFolderId.value)
  } else {
    preUrl.value = notPre
    previewVisible.value = !previewVisible.value
  }


};


//文件重命名
//秒传文件无法重命名
//根据名称判断
const reNameVisible = ref(false)
const reNameValue = ref()
const selectReNameId = ref();
const selectReNameFileName = ref();
const reNameShow = (fileId, fileName) => {
  reNameVisible.value = !reNameVisible.value
  selectReNameId.value = fileId
  selectReNameFileName.value = fileName
}
const reNameBody = reactive({})
const reName = () => {
  console.log("执行重命名，id是" + selectReNameId.value)
  console.log("当前输入的是" + reNameValue.value)
  if (checkFileName(selectReNameFileName.value)) {
    ElMessage.error("秒传文件不允许重命名！");
  } else {
    reNameBody.fileId = selectReNameId.value
    reNameBody.fileName = reNameValue.value
    request.post('/file/rename', reNameBody).then((res) => {
      if (res.code == '200') {
        ElMessage.success('更新成功')
        reNameVisible.value = !reNameVisible.value
      } else {
        ElMessage.error('登录失败')
      }
    })
  }
}
// 检查文件名是否符合数字+下划线格式
const checkFileName = (fileName) => {
  const regex = /^\d+_/;
  return regex.test(fileName);
}

//上传文件
const uploadData = ref({
  folderId: curFolderId.value, // 添加 folderId 参数
});
// 监听 curFolderId 的变化，并动态更新 uploadData 中的 folderId
watch(curFolderId, (newVal) => {
  uploadData.value.folderId = newVal; // 更新 uploadData 中的 folderId
});
const handleUpload = (res, file, fileList) => {
  console.log(res, file, fileList);
  //init();
  load()
  if (res.code == '200') {
    if (res.msg == "请求成功") {
      ElMessage.success("上传成功")
    } else {
      ElMessage.success("已存在文件，秒传完成")
    }

  } else {
    ElMessage.error("上传失败，请重新尝试")
  }
}

//删除文件
const deleteToRecycle = (id) => {
  console.log("当前id是" + id)
  request.post('/file/toRecycle/' + id).then(res => {
    init();

    console.log(res)
  })
}

//下载文件
const download = (url) => {
  const link = document.createElement('a');
  link.href = url // 设置下载链接
  document.body.appendChild(link); // 添加到页面中
  link.click(); // 触发点击事件
  document.body.removeChild(link); // 下载后移除链接
}


//分享文件
const shareFileView = ref(false);
const shareFileInit = ref({})//文件信息
const shareFIleRes = ref({})//需要保存的信息
const shareTimeRadio = ref(1)//文件有效时间
const shareFileDialog = (row) => {
  shareFileInit.value = row
  shareFileView.value = !shareFileView.value
}
const shareFile = () => {
  //表单绑定的数据
  // console.log("验证码是"+shareFIleRes.value.code)
  // console.log("过期时间是"+shareFIleRes.value.expirationTime)
  shareFIleRes.value.downUrl = shareFileInit.value.fileUrl
  shareFIleRes.value.fileName = shareFileInit.value.fileName
  shareFIleRes.value.fileId = shareFileInit.value.fileId

  request.post('/share/add?day=' + shareTimeRadio.value, shareFIleRes.value).then((res) => {
    //console.log(res)
    if (res.code == "200") {
      ElMessage.success("生成分享链接成功！")
    } else {
      ElMessage.error("请重新尝试吧")
    }
    shareFileView.value = !shareFileView.value
  })


}

//大文件上传--分片上传
const bigFileView = ref(false);
const bigFileViewDialog = () => {
  bigFileView.value = !bigFileView.value;
}
// 定义响应式数据
const uploadRef = ref(null);
const urlPrefix = 'http://localhost:9090';
const headers = {
  'Content-Type': 'multipart/form-data'
};
const singleFilePart = reactive({
  file: '',
  fileList: [],
  partIndex: 0,  // 当前分片
  partNum: 0, // 总分片数
  fileName: '',   // 文件名
  fileUid: '',   // 文件uuid
});
const uploadProgress = reactive({
  percentage: 0, // 进度条百分比
  uploading: false, // 是否正在上传

  percentage1: 0, // 进度条百分比
  uploading1: false, // 是否正在上传
});

// 文件选择
const selectSinglePartFile = async (file, fileList) => {
  singleFilePart.file = file;
  singleFilePart.fileList = [file];
  singleFilePart.fileName = file.name;
  singleFilePart.fileSize = file.size;
  uploadProgress.percentage = 0; // 清除进度条

  // 计算文件的 MD5 值
  const fileReader = new FileReader();
  const spark = new SparkMD5.ArrayBuffer();
  const buffer = await new Promise((resolve) => {
    fileReader.readAsArrayBuffer(file.raw);
    fileReader.onload = (e) => {
      resolve(e.target.result);
    };
  });
  spark.append(buffer);
  singleFilePart.fileMd5 = spark.end();

  console.log("单文件分片上传->选中的文件：", singleFilePart.file);
  console.log("文件 MD5 值：", singleFilePart.fileMd5);
  console.log("文件大小：", singleFilePart.fileSize);
};

// 文件移除
const removeSingleFilePart = (file, fileList) => {
  singleFilePart.file = '';
  uploadProgress.percentage = 0; // 清除进度条
  console.log("单文件分片上传->移除选中的文件：", singleFilePart.file);
};

// 分片上传
const singleFilePartUpload = () => {
  let url = urlPrefix + "/file/singleFilePartUpload";
  let partSize = 8; //MB
  singleFilePart.fileUid = singleFilePart.file.uid;
  singleFilePart.partNum = Math.ceil(singleFilePart.file.size / 1024 / 1024 / partSize); // 8MB一片
  let completedParts = 0; // 已上传的分片数

  for (let i = 0; i < singleFilePart.partNum; i++) {
    var fileParam = new FormData();
    fileParam.append('filePart', singleFilePart.file.raw.slice(i * 1024 * 1024 * partSize, (i + 1) * 1024 * 1024 * partSize));
    fileParam.append('partIndex', i);
    fileParam.append('partNum', singleFilePart.partNum);
    fileParam.append('fileName', singleFilePart.fileName);
    fileParam.append('fileUid', singleFilePart.fileUid);
    fileParam.append("folderId", curFolderId.value);
    fileParam.append('fileMd5', singleFilePart.fileMd5);
    fileParam.append('fileSize', singleFilePart.fileSize);

    axios.post(url, fileParam, {headers: headers})
        .then(resp => {
          let res = resp.data;
          if (res.code === '200') {
            //进度条
            completedParts++;
            uploadProgress.percentage = Math.floor((completedParts / singleFilePart.partNum) * 100); // 更新进度条

            console.log(`当前分片 ${i} 上传成功！`);
            if (completedParts === singleFilePart.partNum) {
              ElMessage.success("文件上传完成")
              uploadProgress.percentage = 0;
              load()
              bigFileView.value = !bigFileView.value;
            }
          } else {
            console.log(`当前分片 ${i} 上传失败！`);
            // 假设使用了 ElementPlus 的消息提示，需要正确引入
            // this.$message.error(res.msg);
            ElMessage.error("文件上传失败")
            uploadProgress.percentage = 0;
          }
        })
        .catch(error => {
          console.error('上传失败:', error);
          // 假设使用了 ElementPlus 的消息提示，需要正确引入
          // this.$message.error('上传失败，请重试');
        });
  }
};


//大文件断点续传
const singleFilePartPoint = reactive({
  file: null,
  fileList: [],
  fileData: [],
  partNum: 0,
  fileName: '',
  fileUid: '',
  fileMd5: '',
  isStop: false,
  randomCount: 0
});
//
// const selectSingleFilePartPoint = async (file, fileList) => {
//   singleFilePartPoint.file = file;
//   singleFilePartPoint.fileList = [file];
//   singleFilePartPoint.fileName = file.name;
//   singleFilePartPoint.fileMd5 = SparkMD5.ArrayBuffer.hash(await readFile(singleFilePartPoint.file.raw));
//   console.log("单文件(分片)断点上传->选中的文件：", singleFilePartPoint.fileList);
//   uploadProgress.percentage = 0; // 清除进度条
// };
//
// const removeSingleFilePartPoint = (file, fileList) => {
//   singleFilePartPoint.file = null;
//   console.log("单文件(分片)断点上传->移除选中的文件：", singleFilePartPoint.file);
//   uploadProgress.percentage = 0; // 清除进度条
// };
//
// const singleFilePartPointUpload = async () => {
//   const checkUploadUrl = urlPrefix + "/file/checkUploadFileIndex";
//   const fileUploadUrl = urlPrefix + "/file/singleFilePartPointUpload";
//   const partSize = 8;
//
//   const partNum = Math.ceil(singleFilePartPoint.file.size / 1024 / 1024 / partSize);
//
//   const fileInfo = {
//     fileName: singleFilePartPoint.file.name,
//     fileUid: singleFilePartPoint.file.uid,
//     fileMd5: singleFilePartPoint.fileMd5,
//     fileSize: singleFilePartPoint.file.size,
//     partNum
//   };
//
//   try {
//     const resp = await axios.post(checkUploadUrl, fileInfo);
//     const res = resp.data;
//     if (res.code === '200') {
//
//       let fileInfo = res.data;
//       console.log("已上传文件部分：", fileInfo);
//
//       if (singleFilePartPoint.randomCount!== 0 || fileInfo.parts.length!== 0) {
//         singleFilePartPoint.isStop = false;
//         console.log("该文件之前被模拟过随机停止的情况,此次上传不再随机停止节点了,直接上传还未上传的文件");
//       }
//
//       const random = Math.floor(Math.random() * partNum);
//
//       for (let i = 0; i < partNum; i++) {
//         if (i === random && singleFilePartPoint.randomCount === 0 && fileInfo.parts.length === 0) {
//           singleFilePartPoint.isStop = true;
//           singleFilePartPoint.randomCount++;
//           ElMessage.error("网络波动异常！进度已保存，请稍后尝试继续上传")
//           console.log("随机停止分片节点:", random);
//           break;
//         }
//
//         const iStr = i.toString();
//         if (fileInfo.parts.indexOf(iStr)!== -1) continue;
//
//         fileInfo.partIndex = i;
//         const fileParam = new FormData();
//         fileParam.append('filePart', singleFilePartPoint.file.raw.slice(i * 1024 * 1024 * partSize, (i + 1) * 1024 * 1024 * partSize));
//         fileParam.append('fileInfo', JSON.stringify(fileInfo));
//
//         try {
//           const uploadResp = await axios.post(fileUploadUrl, fileParam);
//           const uploadRes = uploadResp.data;
//           if (uploadRes.code === '200') {
//             console.log(uploadRes);
//             if (i!== uploadRes.msg) {
//               const info = `当前分片 ${i} 上传成功！;返回的分片是 ${uploadRes.msg}`;
//               console.log(info);
//             }
//
//             completedParts++;
//             uploadProgress.percentage = Math.floor((completedParts / partNum) * 100);
//
//             console.log("第"+i+"论")
//             console.log("当前partNum是"+partNum)
//             console.log("当前分片uploadRes.msg"+uploadRes.msg)
//             if (Number(uploadRes.msg) === partNum - 1) {
//               ElMessage.success('单文件(分片)断点上传完成');
//               singleFilePartPoint.randomCount = 0;
//             }
//           } else {
//             ElMessage.error(uploadRes.msg);
//           }
//         } catch (uploadError) {
//           console.error('上传失败:', uploadError);
//           ElMessage.error('上传失败，请重试');
//         }
//       }
//     } else {
//       ElMessage.error(res.msg);
//     }
//   } catch (error) {
//     console.error('请求失败:', error);
//     ElMessage.error('请求失败，请重试');
//   }
// };
//
// const singleFilePartPointStopUpload = () => {
//   singleFilePartPoint.isStop =!singleFilePartPoint.isStop;
// };
//
// const readFile = (file) => {
//   return new Promise((resolve, reject) => {
//     const reader = new FileReader();
//     reader.onload = e => resolve(e.target.result);
//     reader.onerror = e => reject(e);
//     reader.readAsArrayBuffer(file);
//   });
// };
const selectSingleFilePartPoint = async (file, fileList) => {
  singleFilePartPoint.file = file;
  singleFilePartPoint.fileList = [file];
  singleFilePartPoint.fileName = file.name;
  singleFilePartPoint.fileMd5 = SparkMD5.ArrayBuffer.hash(await readFile(singleFilePartPoint.file.raw));
  console.log("单文件(分片)断点上传->选中的文件：", singleFilePartPoint.fileList);
  uploadProgress.percentage1 = 0; // 选择新文件时重置进度条
};

const removeSingleFilePartPoint = (file, fileList) => {
  singleFilePartPoint.file = null;
  uploadProgress.percentage1 = 0; // 移除文件时重置进度条
  console.log("单文件(分片)断点上传->移除选中的文件：", singleFilePartPoint.file);
};

const singleFilePartPointUpload = async () => {
  const checkUploadUrl = urlPrefix + "/file/checkUploadFileIndex";
  const fileUploadUrl = urlPrefix + "/file/singleFilePartPointUpload";
  const partSize = 8;

  const partNum = Math.ceil(singleFilePartPoint.file.size / 1024 / 1024 / partSize);
  singleFilePartPoint.partNum = partNum;

  const fileInfo = {
    fileName: singleFilePartPoint.file.name,
    fileUid: singleFilePartPoint.file.uid,
    fileMd5: singleFilePartPoint.fileMd5,
    fileSize: singleFilePartPoint.file.size,
    partNum
  };

  try {
    const resp = await axios.post(checkUploadUrl, fileInfo);
    const res = resp.data;
    if (res.code === '200') {
      let fileInfo = res.data;
      console.log("已上传文件部分：", fileInfo);

      if (singleFilePartPoint.randomCount !== 0 || fileInfo.parts.length !== 0) {
        singleFilePartPoint.isStop = false;
        console.log("该文件之前被模拟过随机停止的情况,此次上传不再随机停止节点了,直接上传还未上传的文件");
      }

      const random = Math.floor(Math.random() * partNum);
      let uploadedParts = fileInfo.parts.length;

      for (let i = 0; i < partNum; i++) {
        if (i === random && singleFilePartPoint.randomCount === 0 && fileInfo.parts.length === 0) {
          singleFilePartPoint.isStop = true;
          singleFilePartPoint.randomCount++;
          console.log("随机停止分片节点:", random);
          break;
        }

        const iStr = i.toString();
        if (fileInfo.parts.indexOf(iStr) !== -1) continue;

        fileInfo.partIndex = i;
        const fileParam = new FormData();
        fileParam.append('filePart', singleFilePartPoint.file.raw.slice(i * 1024 * 1024 * partSize, (i + 1) * 1024 * 1024 * partSize));
        fileParam.append('fileInfo', JSON.stringify(fileInfo));

        try {
          const uploadResp = await axios.post(fileUploadUrl, fileParam);
          const uploadRes = uploadResp.data;
          if (uploadRes.code === '200') {
            console.log(uploadRes);
            if (i !== Number(uploadRes.msg)) {
              const info = `当前分片 ${i} 上传失败！;返回的分片是 ${uploadRes.msg}`;
              console.log(info);
            }
            uploadedParts++;
            uploadProgress.percentage1 = Math.floor((uploadedParts / partNum) * 100);

            if (Number(uploadRes.msg) === partNum - 1) {
              singleFilePartPoint.randomCount = 0;
              ElMessage.success('单文件(分片)断点上传完成');
              uploadProgress.percentage1 = 100;
            }
          } else {
            ElMessage.error(uploadRes.msg);
          }
        } catch (uploadError) {
          console.error('上传失败:', uploadError);
          ElMessage.error('上传失败，请重试');
        }
      }
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    console.error('请求失败:', error);
    ElMessage.error('请求失败，请重试');
  }
};

const singleFilePartPointStopUpload = () => {
  singleFilePartPoint.isStop = !singleFilePartPoint.isStop;
};

const readFile = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = e => resolve(e.target.result);
    reader.onerror = e => reject(e);
    reader.readAsArrayBuffer(file);
  });
};


//文件夹逻辑------------------------------------------------


// 获取当前文件夹详细信息
const curFolderDetail = (folderId) => {
  return folders.value.find(f => f.folderId === folderId) || null;
};
// 动态计算当前文件夹的详细信息
const folderDetail = computed(() => curFolderDetail(curFolderId.value));


// 动态生成导航路径
const breadcrumb = computed(() => {
  const path = [];
  let currentFolder = curFolderDetail(curFolderId.value); // 使用动态计算的当前文件夹
  while (currentFolder) {
    path.unshift(currentFolder); // 把当前文件夹添加到路径的前面
    currentFolder = folders.value.find(f => f.folderId === currentFolder.parentFolderId); // 找到父文件夹
  }
  return path;
});

// 切换文件夹
const goToFolder = (folderId) => {
  curFolderId.value = folderId;
  //init()
  load()
};

//新建文件夹

const newFolderVisible = ref(false)
const showAddFolder = () => {
  newFolderVisible.value = !newFolderVisible.value
}

const addFolder = () => {

  //文件名输入了
  // 创建一个新的对象副本，避免 Vue 响应式对象中的循环引用
  const folderData = JSON.parse(JSON.stringify(newFolder.value))

  folderData.parentFolderId = curFolderId.value

  request.post('/folder/add', folderData).then((res) => {
    if (res.code == "200") {
      ElMessage.success("创建成功")
      newFolderVisible.value = !newFolderVisible.value
      load()
    } else {
      ElMessage.error("已创建该文件夹，请更换文件夹名")
    }

  })
}

//文件移动导航生成
const selectmoveFileId = ref();
const selectFolderId = ref();
const currentParentId = ref(1);
const currentFolders = ref([]);

const moveFileView = ref(false)
const moveFileDialog = (row) => {
  moveFileView.value = !moveFileView.value
  selectmoveFileId.value = row.fileId
}

onMounted(async () => {
  currentFolders.value = folders.value.filter(folder => folder.parentFolderId === currentParentId.value);
});

const selectFolder = (folderId) => {
  currentParentId.value = folderId;
  selectFolderId.value = folderId;
  console.log("当前选择的文件夹为" + selectFolderId.value)
  currentFolders.value = folders.value.filter(folder => folder.parentFolderId === currentParentId.value);
};

const goBack = () => {
  const parentFolder = folders.value.find(folder => folder.folderId === currentParentId.value);
  if (parentFolder) {
    currentParentId.value = parentFolder.parentFolderId;
    selectFolderId.value = parentFolder.parentFolderId;
    console.log("回退，当前选择的文件夹为" + selectFolderId.value)
    currentFolders.value = folders.value.filter(folder => folder.parentFolderId === currentParentId.value);
  }
};

// 根据当前选择的文件夹 ID 获取文件夹名称
const getCurrentFolderName = () => {
  const currentFolder = folders.value.find(folder => folder.folderId === selectFolderId.value);
  return currentFolder ? currentFolder.folderName : '未知文件夹';
};


const moveFile = async () => {
  console.log("文件移动到", selectFolderId.value, "当前文件Id", selectmoveFileId.value);
  const formData = new FormData();
  formData.append('folderId', selectFolderId.value);
  formData.append('selectmoveFileId', selectmoveFileId.value);

  await axios.post(urlPrefix + '/file/moveFile', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then((res) => {
    if (res.data.code === '200') {
      ElMessage.success('文件移动成功');
      load()
      // 如果有需要，可以在这里添加刷新文件列表等操作
    } else {
      ElMessage.error('文件移动失败');
    }
  }).catch((error) => {
    console.error('请求出错:', error);
    ElMessage.error('请求出错，请稍后重试');
  });
};


//回收新增的
const recycle=(id)=>{
  console.log("即将要恢复的id:"+id)
  request.post('/file/recover/'+id).then((res)=>{
    if(res.code=='200')
    {
      ElMessage.success('文件恢复成功')
      load()
    }
    else
    {
      ElMessage.error('文件恢复失败')
    }
  })

}


</script>

<style lang="scss" scoped>
// 新的用法，使用 @use
@use "@/assets/file.list.scss";

.link-style {
  color: #4da6e6; /* 设置链接的颜色为蓝色 */
  cursor: pointer; /* 鼠标悬停时显示手型光标 */
  text-decoration: none; /* 默认去掉下划线 */
}

.link-style:hover {
  text-decoration: underline; /* 鼠标悬停时加下划线 */
  color: #5fa076; /* 鼠标悬停时改变颜色 */
}
</style>
